var express = require('express');
var hbs = require('hbs');
var fs = require('fs');
var path = require('path');
var favicon = require('serve-favicon');
var winston = require("./common/Logger/Logger").winston;
var compression = require('compression');

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//初始化AccessToken
var accessTokenController = require('./app_server/controllers/AccessTokenController');
accessTokenController.initAccessToken();

var routes = require('./app_server/routes/index');

var app = express();

var ua = require('express-ua');
app.use(ua);


// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'hbs');
hbs.registerHelper('static', function (name) {
    return require('./common/utils/static.js').map(name);
});
hbs.registerPartials(__dirname + '/views/partial');

/**
 * HandelBus 函数注册
 * add by yan
 */
hbs.registerHelper('formatPrice', function (money, options) {
    if (money == "") {
        return "";
    }
    if (money) {
        money = parseInt(money) * 0.01;
    }
    if (/[^0-9\.\-\+]/.test(money)) {
        return '¥' + money + '/小时';
    }
    money = parseFloat(money) + "";
    if ('NaN' == money) {
        return '未设定';
    }
    var money_flag = "";
    if (money.indexOf("-") != -1) {
        money = money.replace(/-/g, "");
        money_flag = "-";
    }
    money = money.replace(/^(\d*)$/, "$1.");
    money = (money + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    money = money.replace(".", ",");
    var re = /(\d)(\d{3},)/;
    while (re.test(money)) {
        money = money.replace(re, "$1,$2");
    }
    money = money.replace(/,(\d\d)$/, ".$1");
    var money = money_flag + "¥" + money.replace(/^\./, "0.") + '/小时';
    return money;
});
hbs.registerHelper('formatConsumption', function (money) {
    if (money == "") {
        return "";
    }
    if (money) {
        money = parseInt(money) * 0.01;
    }
    if (/[^0-9\.\-\+]/.test(money)) {
        return money;
    }
    money = parseFloat(money) + "";
    if ('NaN' == money) {
        return "0.00";
    }
    var money_flag = "";
    if (money.indexOf("-") != -1) {
        money = money.replace(/-/g, "");
        money_flag = "-";
    }
    money = money.replace(/^(\d*)$/, "$1.");
    money = (money + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    money = money.replace(".", ",");
    var re = /(\d)(\d{3},)/;
    while (re.test(money)) {
        money = money.replace(re, "$1,$2");
    }
    money = money.replace(/,(\d\d)$/, ".$1");
    var money = money_flag + "" + money.replace(/^\./, "0.")
    return '￥' + money + '/人';
});
hbs.registerHelper('formatPerCapita',function (price) {
    if (price == "") {
        return "";
    }
    if (price) {
        price = parseInt(price) * 0.01;
    }
    if (/[^0-9\.\-\+]/.test(price)) {
        price = price.toFixed(2);
        return '¥' + price + '/人';
    } else {
        return '¥' + price + '/人';
    }
})
hbs.registerHelper('formatDistance', function (distance) {
    distance = Math.sqrt(distance)*100*1000;
    if (distance < 1000) {
        distance = Math.round(distance)+"m";
    } else if (distance > 1000 && distance < 100000) {
        let jl = distance / 1000.0;
        distance = jl.toFixed(1) + "km";
    } else {
        distance = ">100km";
    }
    return distance;
});
hbs.registerHelper('formatDoughnutCenter', function (score) {
    let s = score;
    if ( s >= 9.5) {
        return './img/010-center-score.png';
    } else if (8.5 <= s && s< 9.5) {
        return './img/009-center-score.png';
    } else if (7.5 <= s && s< 8.5) {
        return './img/008-center-score.png';
    } else if (6.5 <= s && s< 7.5) {
        return './img/007-center-score.png';
    } else if (5.5 <= s && s< 6.5) {
        return './img/006-center-score.png';
    } else if (4.5 <= s && s< 5.5) {
        return './img/005-center-score.png';
    } else if (3.5 <= s && s< 4.5) {
        return './img/004-center-score.png';
    } else if (2.5 <= s && s< 3.5) {
        return './img/003-center-score.png';
    } else {
        return './img/002-center-score.png';
    }
});
hbs.registerHelper('formatDoughnut', function (score) {
    let s = score;
    if ( s >= 9.5) {
        return './img/010-wx-score.png';
    } else if (8.5 <= s && s< 9.5) {
        return './img/009-wx-score.png';
    } else if (7.5 <= s && s< 8.5) {
        return './img/008-wx-score.png';
    } else if (6.5 <= s && s< 7.5) {
        return './img/007-wx-score.png';
    } else if (5.5 <= s && s< 6.5) {
        return './img/006-wx-score.png';
    } else if (4.5 <= s && s< 5.5) {
        return './img/005-wx-score.png';
    } else if (3.5 <= s && s< 4.5) {
        return './img/004-wx-score.png';
    } else if (2.5 <= s && s< 3.5) {
        return './img/003-wx-score.png';
    } else {
        return './img/002-wx-score.png';
    }
});
hbs.registerHelper('formatMovieScore', function (score) {
    let t = score.toFixed(0);
    if (t == score){
        return score + '.0';
    } else {
        return score;
    }
});
hbs.registerHelper('ALBUM_POSTER',function (album_id,wx_poster) {
    return require('./config').cdn.imgs + '/ALBUM/'+ album_id + '/'+ wx_poster;
});
hbs.registerHelper('CINEMA_BANNER_POSTER',function (banner_poster) {
    return require('./config').cdn.imgs + '/' + banner_poster;
});
hbs.registerHelper('MOVIE_BANNER_POSTER',function (banner_poster) {
    return require('./config').cdn.imgs + '/' + banner_poster;
});
hbs.registerHelper('MOVIE_POSTER',function (mid,poster) {
    return require('./config').cdn.imgs + '/MOVIE/'+ mid + '/POSTER/'+ poster ;
});
hbs.registerHelper('CINEMA_POSTER',function (cinema_code,poster) {
    let a = poster.split('/');
    if (a.length>1){
        let p = a[a.length-1];
        return require('./config').cdn.imgs + '/' +cinema_code + '/pic/'+ p;
    }else {
        return require('./config').cdn.imgs + '/' +cinema_code + '/pic/'+ cinema_code + '.jpg';
    }
});
hbs.registerHelper('random',function (num) {
    return Math.random();
});
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser(require('./config').app.appsecret));
app.use(compression()); //use compression
app.use(express.static(path.join(__dirname, 'public'), {
    maxAge: 7 * 24 * 60 * 60
}));
app.use(require('./common/Logger/RequestLogger').create(winston));

// app.use(function (req, res, next) {
//     var url = req.originalUrl;
//     var openid = '0';
//     if (req.signedCookies.openid || req.signedCookies.open_id) {
//         openid = req.signedCookies.openid || req.signedCookies.open_id;
//     };
//     if (openid == '' || openid == 'undefined' || openid == null) {
//         next()
//     }else  if (url=='/member') { //如果是入口页面，不判断
//         next();
//     } else {//其他如果openi不存在手机号，跳转到登录页面
//         console.log('11111111111111',false)
//         tool.baseDao('app.js','select phone_number from member_user where openid=? ',openid,function (result) {
//             if(result.isSuccess&&result.rows.length>0&&result.rows[0]['phone_number'].length==11) {
//                 next();
//             }else{
//                 res.render('member',{
//                     title:'会员注册'
//                 })
//             }
//         })
//     }
// });

app.use('/', routes);
// app.use('/users', users);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
// var http =require('http');
// var https = require('https')
//     ,fs = require("fs");
//
// var options = {
//     key: fs.readFileSync('../key/2_weixin.tooking.cn.key'),
//     cert: fs.readFileSync('../key/1_weixin.tooking.cn_bundle.crt')
// };
// http.createServer(app).listen(809);
// https.createServer(options,app).listen(443);

module.exports = app;
